#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int threeSumClosest(int* nums, int numsSize, int target);
int compare_int(const int* o1, const int* o2);

int main()
{
	int num[] = { 1, 2, 5, 10, 11 }, numsSize = 5, target = 12;
	int res = threeSumClosest(num, numsSize, target);
	printf("%d\n", res);
	return 0;
}

int threeSumClosest(int* nums, int numsSize, int target)
{
	qsort(nums, numsSize, sizeof(int), &compare_int);

	int res = INT_MAX;
	for (int left = 0; left < numsSize - 2; left++) {
		int mid = left + 1, right = numsSize - 1, sum = 0;
		while (mid < right) {
			sum = nums[left] + nums[mid] + nums[right];
			int sub = sum - target;
			if (abs(res) > abs(sum - target))
				res = sum - target;
			if (sub < 0) mid++;
			else right--;
		}
	}

	return res + target;
}

int compare_int(const int* o1, const int* o2)
{
	int sub = *o1 - *o2;
	if (sub > 0)		return 1;
	else if (sub < 0)	return -1;
	else				return 0;
}
